import { createBrowserRouter, Navigate, RouteObject } from 'react-router-dom';
import React, { lazy, Suspense } from 'react';
import App from '@/App';
import Loading from '@/pages/Loading';
import { getToken } from '@/utils/token';
import { message } from 'antd';
import { SwapOutlined, UploadOutlined, HomeOutlined } from '@ant-design/icons';
import config from '@/config/index'
const pageFiles: any = import.meta.glob('@/pages/*/*.tsx');
const pages = {} as any;
Object.keys(pageFiles).forEach((key: string) => {
	pages[key.replace('/src/pages/', '').replace(/\/[^/]+\.tsx$/, '')] = pageFiles[key]
})

console.log('pages', pages);


interface IRouterMap {
  [key: string]: {
    label: string;
    icon: React.ReactNode;
  }
}

export const routerMap: IRouterMap = {
  '/': { label: '首页', icon: <HomeOutlined /> },
  'articlePublish': { label: '文章发布', icon: <UploadOutlined /> },
  'billList': { label: '记账本', icon: <SwapOutlined /> },
}

const LazyComponent = (pathInPages: string) => {
  const Component = lazy(pages[pathInPages]);
  // const Component = lazy(() => import(/* @vite-ignore */`@/pages/${pathInPages}`));
  document.title = config.APP_NAME + ' - ' + pathInPages;
  return (
    <Suspense fallback={<Loading />}>
      <Component />
    </Suspense>
  );
};

//HOC高阶组件：参数或返回值是一个组件的组件
const AuthRoute = ({ children }: {children: React.ReactElement<any, any>}) => {
  const token = getToken();
  if (token) return <>{children}</>
  else {
    message.error('登录授权已失效，请重新登陆');
    return <Navigate to='/login' replace></Navigate>
  }
}

const routeList: Array<RouteObject> = [
  {
    path: '/login',
    element: LazyComponent('Login')
  },
  {
    path: '/',
    element: <AuthRoute children={ <App /> } />,
    children: [
      {
        path: '', //默认跳转：path置空 或 index: true(此时不能写path属性)
        // element: withKeepAlive(<AuthRoute children={ LazyComponent('Home') } />, { cacheId: 'home' })  //必须是懒加载组件，若为静态加载组件，则会出现没有element组件警告，并且不能正常显示
        element: <AuthRoute children={ LazyComponent('Home') } />
      },
      {
        path: 'articlePublish',
        element: <AuthRoute children={ LazyComponent('ArticlePublish') } />
      },
      {
        path: 'billList',
        caseSensitive: false, //caseSensitive匹配大小写，但只能匹配 path为小写，地址栏为大写的情况。例如：有'/List'和'/list'，要实现正常匹配，必须把'/list'写在前面，且caseSensitive: true.
        element: <AuthRoute children={ LazyComponent('BillList') } />,
        children: [
          {
            path: '',
            element: <AuthRoute children={ LazyComponent('BillList/Layout') } />,
            children: [
              {
                path: '',
                element: <AuthRoute children={ LazyComponent('BillList/Month') } />
              },
              {
                path: 'yearBill',
                element: <AuthRoute children={ LazyComponent('BillList/Year') } />
              }
            ]
          },
          {
            path: 'newBill',
            element: <AuthRoute children={ LazyComponent('BillList/New') } />
          }
        ]
      }
    ]
  },
  {
    path: '*',
    element: LazyComponent('NotFound')
  }
];

export default createBrowserRouter(routeList);
